﻿
CREATE PROCEDURE [dbo].[DepartmentsInsert]
(
	@Name varchar(100),
	@ShortName varchar(20),
	@DeliveryDuration tinyint,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intNextId int
	SET NOCOUNT ON

IF (@Name Is Null) OR (@ShortName Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (ltrim(@Name) = '') OR (ltrim(@ShortName) = '')
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Незаполнено наименование или короткое наименование!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF EXISTS (SELECT TOP 1 ID FROM [CO].[Departments] WHERE (Name = @Name OR ShortName = @ShortName) AND ToDelete = 0)
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Дублируется наименование или короткое наименование!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF NOT EXISTS (SELECT DepartmentId FROM PR.DepartmentOptions WHERE DepartmentId = 0 ) 
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Изменять данные справочников можно только в офисе!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @intNextId = max(Id + 1) FROM [CO].[Departments]

BEGIN TRAN 
--добавляем категории расчета дефектуры для нового подразделения
EXEC [dbo].[DefekturaCategoriesVsDepartmentsInsert] 1, @intNextId, 1, NULL, @MD, @MW
EXEC [dbo].[DefekturaCategoriesVsDepartmentsInsert] 2, @intNextId, 1, NULL, @MD, @MW
EXEC [dbo].[DefekturaCategoriesVsDepartmentsInsert] 3, @intNextId, 1, NULL, @MD, @MW
EXEC [dbo].[DefekturaCategoriesVsDepartmentsInsert] 4, @intNextId, 1, NULL, @MD, @MW
EXEC [dbo].[DefekturaCategoriesVsDepartmentsInsert] 5, @intNextId, 1, NULL, @MD, @MW

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

	SET NOCOUNT OFF;
INSERT INTO [CO].[Departments] (Id, [Name], [ShortName], DeliveryDuration, [Note], [MD], [MW]) 
VALUES (@intNextId, @Name, @ShortName, @DeliveryDuration, @Note, @MD, @MW);
	
COMMIT

SELECT Id, Name, ShortName, DeliveryDuration, Note, MD, MW FROM CO.Departments WHERE (Id = @intNextId)
RETURN 0
